package com.example.charpter06;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.charpter06.util.FileUtil;

import java.io.File;

public class ImageWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_content;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_write);
        iv_content = findViewById(R.id.iv_content);

        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_read).setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_save:
                String filename  =System.currentTimeMillis() +"png";
                //获取当前app的私有下载目录
                path = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString()+ File.pathSeparator+filename;

                //从指定资源文件中获取位图对象
                Bitmap b1 = BitmapFactory.decodeResource(getResources(),R.drawable.apex);
                //把位图文件保存为图片文件
                FileUtil.saveImage(path,b1);
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_read:
               Bitmap b2 =  FileUtil.openImage(path);
                iv_content.setImageBitmap(b2);
                break;
        }
    }
}